# -*- coding:utf-8 -*-
from agt2 import forms
from agt2.decorators import render_to
from agt2.models import Game, Squad, User, Unit, Task, Hint, Key

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.views.generic import list_detail, create_update
from django.contrib.auth.decorators import user_passes_test

from django.forms.models import modelformset_factory

import hashlib, random

def index(request):
    return render_to_response('agt2/base.html', {'request' : request})

@login_required
@user_passes_test(lambda u: u.groups.get(id__exact=1))
def my_author_games(request):
    user = request.user
    qs = user.author.all()
    return  list_detail.object_list(
        request,
        queryset = qs,
    )

@login_required
# проверка редактирует ли автор
@render_to('agt2/game_scenario.html')
def author_game_scenario(request, object_id):
    game = get_object_or_404(Game, pk=object_id)
    TaskFormset = modelformset_factory(Task, extra = 1)

    if request.method == 'POST':
        formset = TaskFormset(request.POST)
        if formset.is_valid():
            for form in formset.forms:
                if form.instance.id != None:
                    if form.is_valid(): form.save()
                else:
                    if form.is_valid():
                        task = form.save(commit=False)
                        task.game = game
                        task.save()
                        key = Key(text = hashlib.md5('awd').hexdigest(), task = task)
                        key.save()
    else:
        formset = TaskFormset(queryset = game.tasks.all())

    return { 'object' : game, 'formset' : formset }

@login_required
@render_to('agt2/user_confirm_delete.html')
@user_passes_test(lambda u: u.leader.count() != 0)
def my_squad_delete(request):
    if request.method == 'POST':
        team = request.user.leader.all()[0]
        team.is_active = False
        team.save()
        return redirect('/squad')
    else:
        return { 'user' : request.user }

def my_squad_update(request):
    squad = get_object_or_404(Squad, pk=request.user.squad)
    
    return create_update.update_object(
        model = Squad,
        object_id = squad
        )

def my_profile_update(request):
    # TODO: Show only custom fields. Update model to switch the context.
    return create_update.update_object(
        request,
        form_class = forms.ProfileForm,
        object_id = request.user.id,
        template_name = 'agt2/user_form.html',
        login_required = True,
        post_save_redirect = '/profile',
    )

@login_required
@render_to('agt2/user_confirm_delete.html')
def my_profile_delete(request):
    if request.method == 'POST':
        user = request.user
        user.is_active = False
        user.save()
        return redirect('/')
    else:
        return { 'user' : request.user }

def squad_request_create(request):
    pass

def squad_request_update(request):
    pass

@login_required
@render_to('agt2/game/current_level.html')
def game_current_level(request, object_id):
    game = get_object_or_404(Game, pk=object_id)
    KeyFormset = modelformset_factory(Key, extra = 0)

    # выбрать все задания (Task), кроме решенных (Solved) и вернуть первое
    task = game.tasks.all()
    return {
        'tasks'   : task,
    }
